import 'dart:convert';
import 'package:fenzi/pages/list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fenzi/pages/edit.dart';
import 'package:fenzi/global.dart';
import 'package:fenzi/manager/main_manager.dart';
import 'package:provider/provider.dart';

class IndexPage extends StatefulWidget {
  IndexPage({Key key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Global.backgroundColor),
        toolbarHeight: 50,
        elevation: 0,
        title: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(width: 90),
            Text(
              "随份子",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: Global.backgroundColor,
                fontSize: 15,
                fontWeight: FontWeight.w800,
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => EditPage(id: '000', data: {
                      "spending": false,
                      "date": DateTime.now().toString().substring(0, 10),
                      "name": "",
                      "relation": "",
                      "co": "",
                      'type': 'other',
                      "remark": ""
                    }),
                  ),
                );
              },
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 6, 10, 6),
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                  border: Border.all(color: Global.primaryColor, width: 1),
                  borderRadius: BorderRadius.circular(40),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.add_circle_outlined,
                      color: Global.primaryColor,
                      size: 18,
                    ),
                    SizedBox(width: 5),
                    Text(
                      '记一笔',
                      style: TextStyle(
                        color: Global.primaryColor,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(color: Global.cardBackgroundColor),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              TotalHeader(),
              Types(type: 'male'),
              Types(type: 'famale'),
              Types(type: 'child'),
              Types(type: 'friend'),
              Types(type: 'other'),
            ],
          ),
        ),
      ),
    );
  }
}

class TotalHeader extends StatefulWidget {
  TotalHeader({Key key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _TotalHeaderState();
}

class _TotalHeaderState extends State<TotalHeader> {
  double spendingTotal = 0;
  double deSpendingTotal = 0;

  double getTotalDiffCount(allLocalCache) {
    setState(() {
      spendingTotal = 0;
      deSpendingTotal = 0;
    });

    allLocalCache.forEach((item) {
      setState(() {
        if (json.decode(item['data'])['spending']) {
          spendingTotal =
              spendingTotal + double.parse(json.decode(item['data'])['co']);
        } else {
          deSpendingTotal =
              deSpendingTotal + double.parse(json.decode(item['data'])['co']);
        }
      });
    });
    return spendingTotal - deSpendingTotal;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    var diff = getTotalDiffCount(_mainManager.allLocalCache);
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 110,
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Global.primaryColor,
      ),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                "￥",
                style: TextStyle(
                  color: Global.backgroundColor,
                  fontSize: 17,
                  fontWeight: FontWeight.w500,
                  height: 2,
                ),
              ),
              Text(
                '${diff <= 0 ? "" : "-"}${diff.abs().toStringAsFixed(0)}',
                style: TextStyle(
                  color: Global.backgroundColor,
                  fontSize: 30,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                " 收支差（元）",
                style: TextStyle(
                  color: Global.backgroundColor,
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  height: 2.5,
                ),
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ListPage(type: 'total'),
                      ),
                    );
                  },
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(
                        "查看全部",
                        style: TextStyle(
                          color: Global.backgroundColor,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 12,
                        color: Global.backgroundColor,
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: Text(
                  " 收礼 ￥${deSpendingTotal.toStringAsFixed(0)}",
                  style: TextStyle(
                    color: Global.backgroundColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  " 送礼 ￥${spendingTotal.toStringAsFixed(0)}",
                  style: TextStyle(
                    color: Global.backgroundColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class Types extends StatefulWidget {
  Types({Key key, this.type}) : super(key: key);
  final String type;
  @override
  State<StatefulWidget> createState() => _TypesState();
}

class _TypesState extends State<Types> {
  List dataFilter(list, type) {
    return list
        .where((item) => jsonDecode(item['data'])['type'] == type)
        .toList();
  }

  double filterUnSpendingMoney(list) {
    double total = 0;
    list.forEach((item) {
      if (!json.decode(item['data'])['spending']) {
        total = total + double.parse(json.decode(item['data'])['co']);
      }
    });
    return total;
  }

  double filterSpendingMoney(list) {
    double total = 0;
    list.forEach((item) {
      if (json.decode(item['data'])['spending']) {
        total = total + double.parse(json.decode(item['data'])['co']);
      }
    });
    return total;
  }

  String getTypeName(type) {
    String zhName;
    switch (type) {
      case 'male':
        zhName = '男方';
        break;
      case 'famale':
        zhName = '女方';
        break;
      case 'child':
        zhName = '孩子';
        break;
      case 'friend':
        zhName = '朋友';
        break;
      case 'other':
        zhName = '其他';
        break;
      default:
        zhName = '其他';
    }
    return zhName;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    List ownList = dataFilter(_mainManager.allLocalCache, widget.type);
    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ListPage(type: widget.type),
          ),
        );
      },
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 142,
        padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
        decoration: BoxDecoration(
          color: Global.cardBackgroundColor,
          border: Border(
            bottom: BorderSide(
              color: Global.fontSecondColor.withOpacity(.1),
            ),
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(width: 10),
            Container(
              width: 50,
              height: 122,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset('assets/images/${widget.type}.png'),
                  SizedBox(height: 10),
                  Text(
                    getTypeName(widget.type),
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Global.fontColor,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: 20),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(
                    '共${ownList.length}笔',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w500,
                      color: Global.fontColor,
                    ),
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            Text(
                              '收礼：',
                              style: TextStyle(
                                fontSize: 16,
                                color: Global.fontColor,
                              ),
                            ),
                            Text(
                              '${filterUnSpendingMoney(ownList).toStringAsFixed(0)}元',
                              style: TextStyle(
                                fontSize: 20,
                                color: Color(0xFF10C284),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Row(
                          children: [
                            Text(
                              '送礼：',
                              style: TextStyle(
                                fontSize: 16,
                                color: Global.fontColor,
                              ),
                            ),
                            Text(
                              '${filterSpendingMoney(ownList).toStringAsFixed(0)}元',
                              style: TextStyle(
                                fontSize: 20,
                                color: Color(0xFFE46346),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        "收支差：",
                        style: TextStyle(
                          color: Global.fontColor,
                          fontSize: 16,
                        ),
                      ),
                      Text(
                        '${(filterUnSpendingMoney(ownList) - filterSpendingMoney(ownList)).abs().toStringAsFixed(0)}元',
                        style: TextStyle(
                          color: filterUnSpendingMoney(ownList) >
                                  filterSpendingMoney(ownList)
                              ? Color(0xFF10C284)
                              : Color(0xFFE46346),
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Container(
              height: 20,
              child: Image.asset('assets/images/right-arrow.png'),
            )
          ],
        ),
      ),
    );
  }
}
